package org.shj.spark.streaming;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.broadcast.Broadcast;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.util.LongAccumulator;

public class BlackListWordCount {
	private static volatile Broadcast<List<String>> bclist = null;

	public static void main(String[] args) throws Exception{
		SparkConf conf = new SparkConf().setAppName("BlackListWordCount");
		conf.setMaster("local[*]");
		
		List<String> blackList = new ArrayList<String>();
		blackList.add("fuck");
		blackList.add("cao");
		
		JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(5));
		jsc.sparkContext().setLogLevel("WARN");
		
		bclist = jsc.sparkContext().broadcast(blackList);
		
		JavaReceiverInputDStream<String> stream = jsc.socketTextStream("ubuntu1", 9999);
		
		JavaDStream<String> words = stream.flatMap(new FlatMapFunction<String, String>() {
			private static final long serialVersionUID = 5651679677324590412L;

			@Override
			public Iterator<String> call(String line) throws Exception {
				return Arrays.asList(line.split("\\s+")).iterator();
			}
		});
		
		JavaPairDStream<String, Long> black = words.filter(new Function<String, Boolean>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Boolean call(String v1) throws Exception {
				return bclist.getValue().contains(v1);
			}
		}).countByValue();
		
		black.print();
		
		jsc.start();
		jsc.awaitTermination();
		
		jsc.close();

	}

}
